package com.college.products.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.college.common.pojo.ao.IdleItem;
import com.college.common.pojo.ao.Order;
import com.college.common.pojo.vo.PageVo;
import com.college.products.mapper.IdleItemMapper;
import com.college.products.mapper.OrderMapper;
import com.college.products.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private IdleItemMapper idleItemMapper;

    @Override
    public boolean addOrder(Order order) {
        IdleItem idleItem1 = idleItemMapper.selectByPrimaryKey(order.getIdleId());
        if (idleItem1.getIdleStatus() != 1) {
            return false;
        }
        IdleItem idleItem = new IdleItem();
        idleItem.setId(order.getIdleId());
        idleItem.setUserId(idleItem.getUserId());
        idleItem.setIdleStatus((byte) 2);
        return addOrderHelp(idleItem, order);
    }
    @Transactional(rollbackFor = Exception.class)
    public boolean addOrderHelp(IdleItem idleItem, Order order) {
        IdleItem idleItem1 = idleItemMapper.selectByPrimaryKey(order.getIdleId());
        if (idleItem1.getIdleStatus() != 1) {
            return false;
        }
        if (idleItemMapper.updateByPrimaryKeySelective(idleItem) == 1) {
            return orderMapper.insert(order) == 1;
        }
        return false;
    }

    /**
     * 获取订单信息，同时获取对应的闲置信息
     *
     * @param id
     * @return
     */
    @Override
    public Order getOrder(Long id) {
        Order order = orderMapper.selectByPrimaryKey(id);
        order.setIdleItem(idleItemMapper.selectByPrimaryKey(order.getIdleId()));
        return order;
    }

    /**
     * 根据订单号，查询订单
     *
     * @return
     */
    @Override
    public PageVo<Order> findOrderByNumber(String searchValue, int page, int nums) {
        List<Order> list = orderMapper.getOrderByNumber(searchValue, (page - 1) * nums, nums);

        if (ObjectUtils.isNotEmpty(list)) {
            List<Long> idleIdList = new ArrayList<>();
            for (Order i : list) {
                idleIdList.add(i.getIdleId());
            }
            List<IdleItem> idleItemList = idleItemMapper.findIdleByList(idleIdList);
            Map<Long, IdleItem> map = new HashMap<>();
            for (IdleItem idle : idleItemList) {
                map.put(idle.getId(), idle);
            }
            for (Order i : list) {
                i.setIdleItem(map.get(i.getIdleId()));
            }
        }
        return new PageVo<>(list, 1);
    }

    /**
     * 更新订单状态，无验证，后期修改为定制的更新sql
     * 后期改为在支付时下架闲置
     *
     * @param order
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOrder(Order order) {
        // 不可修改的信息
        order.setOrderNumber(null);
        order.setUserId(null);
        order.setIdleId(null);
        order.setCreateTime(null);
        if (order.getOrderStatus() == 4) {
            // 取消订单,需要优化，减少数据库查询次数
            Order o = orderMapper.selectByPrimaryKey(order.getId());
            if (o.getOrderStatus() != 0) {
                return false;
            }
            IdleItem idleItem1 = idleItemMapper.selectByPrimaryKey(o.getIdleId());
            if (idleItem1.getIdleStatus() == 2) {
                IdleItem idleItem = new IdleItem();
                idleItem.setId(o.getIdleId());
                idleItem.setUserId(idleItem.getUserId());
                idleItem.setIdleStatus((byte) 1);
                if (orderMapper.updateByPrimaryKeySelective(order) == 1) {
                    return idleItemMapper.updateByPrimaryKeySelective(idleItem) == 1;
                }
                return false;
            } else {
                if (orderMapper.updateByPrimaryKeySelective(order) == 1) {
                    return true;
                }
            }
        }
        return orderMapper.updateByPrimaryKeySelective(order) == 1;
    }

    /**
     * 获取我的所有订单
     * 同时查询出对应的闲置信息，
     * 未做分页
     * userId建索引
     *
     * @param userId
     * @return
     */
    @Override
    public List<Order> getMyOrder(Long userId) {
        List<Order> list = orderMapper.getMyOrder(userId);
        if (ObjectUtils.isNotEmpty(list)) {
            List<Long> idleIdList = new ArrayList<>();
            for (Order i : list) {
                idleIdList.add(i.getIdleId());
            }
            List<IdleItem> idleItemList = idleItemMapper.findIdleByList(idleIdList);
            Map<Long, IdleItem> map = new HashMap<>();
            for (IdleItem idle : idleItemList) {
                map.put(idle.getId(), idle);
            }
            for (Order i : list) {
                i.setIdleItem(map.get(i.getIdleId()));
            }
        }
        return list;
    }

    /**
     * 查询用户卖出的闲置
     *
     * @param userId
     * @return
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public List<Order> getMySoldIdle(Long userId) {
        List<IdleItem> list = idleItemMapper.getAllIdleItem(userId);
        List<Order> orderList = null;
        if (ObjectUtils.isNotEmpty(list)) {
            List<Long> idleIdList = new ArrayList<>();
            for (IdleItem i : list) {
                idleIdList.add(i.getId());
            }
            orderList = orderMapper.findOrderByIdleIdList(idleIdList);
            Map<Long, IdleItem> map = new HashMap<>();
            for (IdleItem idle : list) {
                map.put(idle.getId(), idle);
            }
            for (Order o : orderList) {
                o.setIdleItem(map.get(o.getIdleId()));
            }
        }
        return orderList;
    }

    @Override
    public PageVo<Order> getAllOrder(int page, int nums) {
        List<Order> list = orderMapper.getAllOrder((page - 1) * nums, nums);
        if (ObjectUtils.isNotEmpty(list)) {
            List<Long> idleIdList = new ArrayList<>();
            for (Order i : list) {
                idleIdList.add(i.getIdleId());
            }
            List<IdleItem> idleItemList = idleItemMapper.findIdleByList(idleIdList);
            Map<Long, IdleItem> map = new HashMap<>();
            for (IdleItem idle : idleItemList) {
                map.put(idle.getId(), idle);
            }
            for (Order i : list) {
                i.setIdleItem(map.get(i.getIdleId()));
            }
        }
        int count = orderMapper.countAllOrder();
        return new PageVo<>(list, count);
    }

    @Override
    public boolean deleteOrder(long id) {
        return orderMapper.deleteByPrimaryKey(id) == 1;
    }
}
